I have an array of size 8, and I send only the second half of the array to my insertion sort. It successfully sorts only the second half of the array, but there is a statement at the bottom, "Abort trap: 6". Below are my main.cc and my insertionSort.cc files. What is causing the "Abort trap: 6" error?
Here is the output:
Before sorting
9 8 10 2 4 6 50 1
After sorting
9 8 10 2 1 4 6 50
Abort trap: 6
main.cc
Code:
#include <cstdio>
#include "insertionSort.h"
int main() {
// create array
int array[] = {9, 8, 10, 2, 4, 6, 50, 1};
// get size of the array
int size = sizeof(array) / sizeof(array[0]);
// display array before reversing
printf("Before sorting\n");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
// new line
printf("\n");
// sort only the second half of the array
insertionSort(array+(size/2), size);
// display the array again after reversing
printf("After sorting\n");
for (int i = 0;i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
// new line
printf("\n");
} // end of main
insertionSort.cc
Code:
#include "insertionSort.h"
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j+1] = array[j];
j--;
} // end of while loop
// swap
array[j+1] = key;
} // end of for loop
} // end of insertionSort